/**
 * 
 */
package com.redoor.iot.security;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.redoor.iot.mapper.UserMapper;
import com.redoor.iot.model.User;
import com.redoor.iot.service.IMenuService;

/**
 * @author Administrator
 *
 */
@Service("myUserDetailsImpl")
public class MyUserDetailsService implements UserDetailsService {
	@Autowired
	private UserMapper userMapper;

    @Autowired
    private IMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    	User user;
    	try {
        	Map<String, Object> map = new HashMap<>(16);
    		//判断是账号登录或邮箱登录
    		if(userName.contains("@")) {
    			map.put("email", userName);
    		}else {
    			map.put("userAccount", userName);
    		}

    		// 查询用户信息
    		user = userMapper.list(map).get(0);
        } catch (Exception e) {
            throw new UsernameNotFoundException("用户信息数据库查询失败");
        }
        if(user == null){
            throw new UsernameNotFoundException("登录用户不存在");
        } else {
            try {
            	//查询登录用户拥有url资源权限
            	List<String> urls = new ArrayList<String>();
                if(user != null){
                	urls = menuService.listUrl(user.getUserId());
                	//遍历删除为空的权限，包括NULL值和空字符串
                	Iterator<String> iter = urls.iterator();
                	while (iter.hasNext()) {
                        if(StringUtils.isBlank(iter.next())) {
                        	iter.remove();
                        }
                    }
                }
                //把登录用户信息转成json存放进security的authentication中去
        		ObjectMapper om = new ObjectMapper();
        		String loginUserStr = om.writeValueAsString(user);
        		
        		return new MyUser(userName, user.getPassword(),
        				true, true, true, true,
        				AuthorityUtils.commaSeparatedStringToAuthorityList("admin"),
        				loginUserStr,
        				urls);
            } catch (Exception e) {
                throw new UsernameNotFoundException("用户拥有url资源权限查询失败");
            }
        }
    }
}
